<template>
  <div class="flex flex-col">
    <div class="flex justify-between items-center">
      <a-breadcrumb>
        <a-breadcrumb-item>医生管理</a-breadcrumb-item>
        <a-breadcrumb-item>基础信息</a-breadcrumb-item>
      </a-breadcrumb>
      <a-button class="border-none" icon="rollback" @click="rollback">返回列表</a-button>
    </div>
    <a-card
      class="min-h-[68px] rounded my-[10px]"
      :body-style="{padding: '12px 30px', height:'100%'}"
      :bordered="false"
    >
      <div class="flex justify-between items-center mb-2">
        <div class="text-base text-black font-bold">医生信息</div>
        <div>
          <a-button type="primary" class="mr-3" @click="checkQrCode">查看二维码</a-button>
          <a-popconfirm title="确认注销此医生？" @confirm="destory">
            <a-button type="primary" :disabled="docterDetail.UserDestory==2">医生注销</a-button>
          </a-popconfirm>
        </div>
      </div>
      <div class="grid pb-2 grid-cols-2 sm:grid-cols-3 xl:grid-cols-4 gap-1">
        <div class="pt-[15px] bg-white">医生ID: {{docterDetail.UserId}}</div>
        <div class="pt-[15px] bg-white">医生姓名: {{docterDetail.UserName}}</div>
        <div class="pt-[15px] bg-white">身份证号: {{docterDetail.UserName}}</div>
        <div class="pt-[15px] bg-white">性别: {{docterDetail.UserGender==1?'男':'女'}}</div>
        <div class="pt-[15px] bg-white">归属医院: {{docterDetail.DftHospital}}</div>
        <div class="pt-[15px] bg-white">医生科室: {{docterDetail.DiDepartment}}</div>
        <div class="pt-[15px] bg-white">科室职务: {{docterDetail.DiDepartmentJobs||'无'}}</div>
        <!-- <div class="pt-[15px] bg-white">医生状态: {{docterDetail.UserName}}</div> -->
        <div class="pt-[15px] bg-white">个人介绍: {{docterDetail.DiPersonalIntroduction}}</div>
      </div>
    </a-card>
    <a-breadcrumb>
      <a-breadcrumb-item>医生管理</a-breadcrumb-item>
      <a-breadcrumb-item>数据统计</a-breadcrumb-item>
    </a-breadcrumb>
    <div class="my-[10px] grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3">
      <div class="p-[10px] bg-white">
        <div class="flex justify-between items-start">
          <a-statistic prefix="¥" title="月度总收益数" :value="docterDetail.MonthRevenue" />
          <!-- <a-icon type="info-circle" class="mt-[6px]" /> -->
        </div>
      </div>
      <div class="p-[10px] bg-white">
        <div class="flex justify-between items-start">
          <a-statistic prefix="¥" title="年度总收益数" :value="docterDetail.YearRevenue" />
          <!-- <a-icon type="info-circle" class="mt-[6px]" /> -->
        </div>
      </div>
      <div class="p-[10px] bg-white">
        <div class="flex justify-between items-start">
          <a-statistic prefix="¥" title="累计总收益数" :value="docterDetail.TotalRevenue" />
          <!-- <a-icon type="info-circle" class="mt-[6px]" /> -->
        </div>
      </div>
      <div class="p-[10px] bg-white">
        <div class="flex justify-between items-start">
          <a-statistic prefix="¥" title="累计销售额" :value="docterDetail.TotalSales" />
          <!-- <a-icon type="info-circle" class="mt-[6px]" /> -->
        </div>
      </div>
      <div class="p-[10px] bg-white">
        <div class="flex justify-between items-start">
          <a-statistic title="累计开单数" :value="Math.floor(docterDetail.TotalOrders)">
            <template #suffix>
              <span class="leading-7">个</span>
            </template>
          </a-statistic>
          <!-- <a-icon type="info-circle" class="mt-[6px]" /> -->
        </div>
      </div>
    </div>
    <a-row :gutter="12">
      <a-col :lg="24" :xl="16">
        <div class="flex justify-between items-center">
          <a-breadcrumb>
            <a-breadcrumb-item>医生管理</a-breadcrumb-item>
            <a-breadcrumb-item>综合管理</a-breadcrumb-item>
          </a-breadcrumb>
          <div>
            <a-button v-if="selectedKeys[0]==0" type="primary" @click="bindPatient">绑定患者</a-button>
            <!-- <a-button v-if="activekey==0" type="primary">导出患者数据</a-button>
            <a-button v-if="activekey==1" type="primary">导出订单数据</a-button>-->
            <a-button v-if="selectedKeys[0]==3" type="primary" @click="bindAssistant">绑定助理</a-button>
            <!-- <a-button v-if="activekey==3" type="primary">导出助理数据</a-button> -->
          </div>
        </div>
        <a-card
          class="min-h-[300px] h-full rounded my-[10px]"
          :body-style="{padding: '12px', height:'100%'}"
          :bordered="false"
        >
          <a-menu
            mode="horizontal"
            :selectedKeys="selectedKeys"
            type="inner"
            class="bg-transparent mb-2"
            @select="menuChange"
          >
            <template v-for="item in manageList">
              <a-menu-item :key="item.key">{{item.title}}</a-menu-item>
            </template>
          </a-menu>
          <a-table
            ref="table"
            size="small"
            class="h-full"
            :columns="columnsArr[selectedKeys[0]]"
            :dataSource="list"
            :pagination="pagination"
            @change="tableChange"
            :loading="listLoading"
            :rowKey="(record,index)=>{return index}"
          >
            <template v-for="(col, i) in editColumns" :slot="col" slot-scope="text, record">
              <a-input-number
                v-if="record.editable"
                :key="col"
                style="margin: -5px 0"
                v-model.number="text"
                :step="0.1"
                :placeholder="columnsArr[selectedKeys[0]][i].key"
                @change="e => handleChange(e, record.Id, col)"
              />
              <template v-else>
                <span v-if="col=='DsBalance'">¥{{text}}</span>
                <span v-else>{{text}}</span>
              </template>
            </template>

            <template slot="UserBorn" slot-scope="text, record">{{text}}岁</template>
            <template slot="UserOrders" slot-scope="text, record">{{text}}个</template>
            <template slot="UserPay" slot-scope="text, record">{{text}}元</template>
            <template slot="DsTime" slot-scope="text, record">{{text}}天</template>
            <template slot="DiffTime" slot-scope="text, record">
              <span class="font-bold text-red-500">{{text}}天</span>
            </template>

            <template slot="Count" slot-scope="text, record">{{text}}个</template>
            <template slot="YtOrderUserBalance" slot-scope="text, record">{{text}}元</template>
            <template slot="YtOrderUpdatetime" slot-scope="text, record">{{text||'-'}}</template>
            <template
              slot="YtOrderPayStatus"
              slot-scope="text, record"
            >{{['','待支付','已支付','赠送/免费','整单退款','部分退款'][text||0]}}</template>

            <template slot="DsStatus" slot-scope="text,record">
              <a-switch
                checked-children="启用"
                un-checked-children="禁用"
                default-checked
                :checked="text==1"
                :disabled="+record.DsBalance==0"
                @change="changeStatus(record,text)"
                :loading="record.Id==Id"
              />
            </template>

            <template slot="UserAvatar" slot-scope="text, record">
              <img
                :src="`${$store.getters.baseUrl}${text}`"
                alt
                class="rounded-1/2 overflow-hidden w-[50px] h-[50px] mx-auto"
              />
            </template>
            <template slot="action" slot-scope="text, record">
              <div class="editable-row-operations">
                <span v-if="record.editable" class="flex">
                  <a-button type="link" block @click="() => save(record)">保存</a-button>
                  <a-popconfirm title="确认取消修改?" @confirm="() => cancel(record.Id)">
                    <a-button type="link" block>返回</a-button>
                  </a-popconfirm>
                </span>
                <span v-else class="flex">
                  <a-button
                    v-if="selectedKeys[0]==2"
                    type="link"
                    block
                    @click="editService(record.Id)"
                  >修改</a-button>
                  <a-popconfirm title="确认删除助理?" @confirm="delAssistant(record.UserId)">
                    <a-button v-if="selectedKeys[0]==3" type="link" block>删除</a-button>
                  </a-popconfirm>
                </span>
              </div>
            </template>
          </a-table>
        </a-card>
      </a-col>
      <a-col :lg="24" :xl="8">
        <a-breadcrumb>
          <a-breadcrumb-item>医生管理</a-breadcrumb-item>
          <a-breadcrumb-item>生命周期</a-breadcrumb-item>
        </a-breadcrumb>
        <a-card
          class="min-h-[300px] h-full rounded my-[10px]"
          :body-style="{padding: '20px 12px', height:'100%'}"
          :bordered="false"
        >
          <a-timeline
            v-if="timeline.length>0"
            class="min-h-[130px] max-h-[500px] overflow-y-auto pt-2"
          >
            <template v-for="item in timeline">
              <a-timeline-item>
                <p>{{item.StlCreatetime}}</p>
                <p class="font-bold">{{item.StlTitle}}</p>
                <p>{{item.StlInfo}}</p>
              </a-timeline-item>
            </template>
          </a-timeline>
          <div v-else class="flex-1 flex justify-center items-center">
            <a-empty />
          </div>
        </a-card>
      </a-col>
    </a-row>
    <bind-patient ref="bindPatient" @succeed="init" />
    <bind-assistant ref="bindAssistant" @succeed="init" />
    <qrCode ref="qrCode" />
  </div>
</template>

<script>
import {
  destoryDocter,
  getDoctorDetail,
  getTimeline,
  getDoctorOrderList,
  getDoctorServiceList,
  editDoctorService,
  getDoctorAssistantList,
  delDoctorAssistant,
  getDoctorFollowupList,
  getDoctorPatientList,
  doctorBuildPatient,
} from '@/api/index'

import BindPatient from './components/bindPatient.vue'
import BindAssistant from './components/bindAssistant.vue'
import QrCode from './components/qrCode.vue'
const columnsArr = [
  [
    {
      title: '患者姓名',
      dataIndex: 'UserName',
      align: 'center',
      scopedSlots: { customRender: 'UserName' },
    },
    {
      title: '年龄',
      dataIndex: 'UserBorn',
      align: 'center',
      scopedSlots: { customRender: 'UserBorn' },
    },
    {
      title: '订单数',
      dataIndex: 'UserOrders',
      align: 'center',
      scopedSlots: { customRender: 'UserOrders' },
    },
    {
      title: '服务剩余时长',
      className: 'min-w-90p',
      dataIndex: 'DiffTime',
      align: 'center',
      scopedSlots: { customRender: 'DiffTime' },
    },
    {
      title: '消费总额',
      dataIndex: 'UserPay',
      align: 'center',
      width: '120px',
      scopedSlots: { customRender: 'UserPay' },
    },
  ],
  [
    {
      title: '订单号',
      className: 'min-w-90p',
      dataIndex: 'YtOrderSerial',
      align: 'center',
      scopedSlots: { customRender: 'YtOrderSerial' },
    },
    {
      title: '创建时间',
      className: 'min-w-120p',
      dataIndex: 'YtOrderCreatetime',
      align: 'center',
      scopedSlots: { customRender: 'YtOrderCreatetime' },
    },
    {
      title: '更新时间',
      className: 'min-w-120p',
      dataIndex: 'YtOrderUpdatetime',
      align: 'center',
      scopedSlots: { customRender: 'YtOrderUpdatetime' },
    },

    {
      title: '商品名称',
      className: 'min-w-150p',
      dataIndex: 'YtOrderName',
      align: 'center',
      ellipsis: true,
      scopedSlots: { customRender: 'YtOrderName' },
    },
    {
      title: '状态',
      className: 'min-w-90p',
      dataIndex: 'YtOrderPayStatus',
      align: 'center',
      scopedSlots: { customRender: 'YtOrderPayStatus' },
    },
    {
      title: '销售金额',
      className: 'min-w-90p',
      dataIndex: 'YtOrderUserBalance',
      align: 'center',
      ellipsis: true,
      scopedSlots: { customRender: 'YtOrderUserBalance' },
    },
    {
      title: '用户信息',
      className: 'min-w-90p',
      dataIndex: 'YtOrderUserName',
      align: 'center',
      ellipsis: true,
      scopedSlots: { customRender: 'YtOrderUserName' },
    },
    {
      title: '订单来源',
      className: 'min-w-90p',
      dataIndex: 'YtOrderChannel',
      align: 'center',
      ellipsis: true,
      scopedSlots: { customRender: 'YtOrderChannel' },
    },
  ],
  [
    {
      title: '服务名称',
      dataIndex: 'DsName',
      align: 'center',
      ellipsis: true,
      scopedSlots: { customRender: 'DsName' },
    },
    {
      title: '服务信息',
      dataIndex: 'DsInfo',
      align: 'center',
      ellipsis: true,
      scopedSlots: { customRender: 'DsInfo' },
    },
    {
      title: '服务价格',
      dataIndex: 'DsBalance',
      align: 'center',
      scopedSlots: { customRender: 'DsBalance' },
    },
    {
      title: '分成比例',
      dataIndex: 'DsDivide',
      align: 'center',
      scopedSlots: { customRender: 'DsDivide' },
    },
    {
      title: '服务时间',
      dataIndex: 'DsTime',
      align: 'center',
      scopedSlots: { customRender: 'DsTime' },
    },
    {
      title: '状态',
      dataIndex: 'DsStatus',
      align: 'center',
      scopedSlots: { customRender: 'DsStatus' },
    },
    {
      title: '操作',
      dataIndex: 'action',
      align: 'center',
      width: '120px',
      scopedSlots: { customRender: 'action' },
    },
  ],
  [
    {
      title: '头像',
      className: 'min-w-90p',
      dataIndex: 'UserAvatar',
      align: 'center',
      scopedSlots: { customRender: 'UserAvatar' },
    },
    {
      title: '助理姓名',
      dataIndex: 'UserName',
      align: 'center',
      scopedSlots: { customRender: 'UserName' },
    },

    {
      title: '成交订单数',
      className: 'min-w-90p',
      dataIndex: 'Count',
      align: 'center',
      scopedSlots: { customRender: 'Count' },
    },
    {
      title: '操作',
      dataIndex: 'action',
      align: 'center',
      width: '120px',
      scopedSlots: { customRender: 'action' },
    },
  ],
  [
    {
      title: '医生姓名',
      dataIndex: 'DpfuDoctorId',
      align: 'center',
      scopedSlots: { customRender: 'DpfuDoctorId' },
    },
    {
      title: '患者姓名',
      dataIndex: 'DpfuPatientId',
      align: 'center',
      scopedSlots: { customRender: 'DpfuPatientId' },
    },
    {
      title: '医院名称',
      dataIndex: 'hospital',
      align: 'center',
      scopedSlots: { customRender: 'hospital' },
    },
    {
      title: '随访组名',
      className: 'min-w-90p',
      dataIndex: 'DpfuInfo',
      align: 'center',
      scopedSlots: { customRender: 'DpfuInfo' },
    },
    {
      title: '时间',
      className: 'min-w-90p',
      dataIndex: 'DpfuCreatetime',
      align: 'center',
      scopedSlots: { customRender: 'DpfuCreatetime' },
    },
  ],
]
const editColumns = ['DsBalance', 'DsDivide']
export default {
  components: { editDoctorService, BindPatient, BindAssistant, QrCode },
  data() {
    return {
      columnsArr,
      editColumns,
      manageList: [
        {
          key: 0,
          title: '患者列表',
        },
        {
          key: 1,
          title: '业绩列表',
        },
        {
          key: 2,
          title: '服务列表 ',
        },
        {
          key: 3,
          title: '助理列表',
        },
        {
          key: 4,
          title: '随访列表',
        },
      ],
      selectedKeys: [0],
      /**分页 */
      pagination: {
        current: 1, //当前页
        pageSize: 10, //每页条数
        total: 0, //总条数
        // showQuickJumper: true,
        // hideOnSinglePage: true,
        showTotal: (total) => ` ${total} 条数据`,
      },
      /**table数据 */
      list: [],
      //表格Loading
      listLoading: false,
      docterDetail: {},
      timeline: [],
      Id: 0,
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    async init() {
      const uid = this.$route.query.id
      const { data: docterDetail } = await getDoctorDetail({ uid })
      const { data: timeline } = await getTimeline({ uid, pageSize: 10000 })
      this.docterDetail = docterDetail
      this.timeline = [...timeline.Lists]
      this.menuChange({ key: this.selectedKeys[0] })
    },
    menuChange({ key }) {
      this.selectedKeys[0] = key
      this.pagination.current = 1
      this.getList()
    },
    //分页
    tableChange(pagination) {
      this.pagination = pagination
      this.getList()
    },
    /**
     * 获取列表
     */
    async getList() {
      this.listLoading = true
      const { current, pageSize } = this.pagination
      const params = {
        ...{ page: current, pageSize },
        uid: this.docterDetail.UserId,
      }
      try {
        let request
        switch (this.selectedKeys[0]) {
          case 0:
            request = await getDoctorPatientList(params)
            break
          case 1:
            request = await getDoctorOrderList(params)
            break
          case 2:
            request = await getDoctorServiceList(params)
            break
          case 3:
            request = await getDoctorAssistantList(params)
            break
          case 4:
            request = await getDoctorFollowupList(params)
            break
        }
        const { data } = request
        const { Page, PageSize, Total, Lists } = data
        this.list = Lists || []
        this.pagination = {
          current: Page,
          pageSize: PageSize,
          total: Total,
        }
      } catch (error) {
        this.list = []
        this.$message.error(error)
      } finally {
        this.listLoading = false
      }
    },

    async destory() {
      const id = this.docterDetail.UserId
      try {
        await destoryDocter({ id })
        this.$message.success('操作成功！')
        this.init()
      } catch (error) {
        this.$message.error(error)
      }
    },
    handleChange(value, key, column) {
      console.log('value', value, 'key', key, 'column', column)
      const newData = [...this.list]
      const target = newData.find((item) => key === item.Id)
      if (target) {
        target[column] = value
        this.list = newData
      }
    },
    create() {},
    /**
     * 修改资料
     * @param {*} key
     */
    editService(key) {
      const newData = [...this.list]
      const target = newData.find((item) => key === item.Id)
      target._originalData = { ...target }
      target.editable = true
      if (target) {
        this.list = newData
      }
      console.log('this.list', this.list)
    },
    /**
     * 保存
     * @param {*} key
     */
    async save(record) {
      this.listLoading = true
      const {
        Id: id,
        DsStatus: status,
        DsBalance: balance,
        DsDivide: divide,
      } = record
      const doctorId = this.$route.query.id
      if (!balance && !divide) {
        this.listLoading = false
        this.$message.error('请填写完整信息。')
        return
      }

      try {
        await editDoctorService({
          doctorId,
          id,
          status,
          balance,
          divide,
        })
        const target = this.list.find((item) => id === item.Id)
        target.editable = false
        this.$message.success('修改成功')
      } catch (error) {
        this.$message.error(error)
      } finally {
        this.listLoading = false
      }
    },
    /**
     * 取消修改
     * @param {*} key
     */
    cancel(key) {
      const newData = [...this.list]
      const target = newData.find((item) => key === item.Id)
      console.log('target', target)
      Object.keys(target).forEach((key) => {
        if (key != '_originalData') target[key] = target._originalData[key]
      })
      target.editable = false
      target._originalData = undefined
      if (target) {
        this.list = newData
      }
    },
    /**
     * 切换状态
     * @param {*} userId
     */
    async changeStatus(data = {}, status) {
      try {
        const {
          Id: id,
          DsBalance: balance,
          DsDivide: divide,
          DsStatus: status,
        } = data

        const params = {
          id,
          balance,
          divide,
          status: status == 0 ? 1 : 0,
        }
        const doctorId = this.docterDetail.UserId
        this.Id = id
        await editDoctorService({ ...params, doctorId })
        this.$message.success('修改成功')
        this.init()
      } catch (error) {
        this.$message.error(error)
      } finally {
        console.log('this.userId', this.userId)
        this.Id = 0
      }
    },
    checkQrCode() {
      const qrCode = this.docterDetail.DiQrCodeSource
      this.$refs.qrCode.open(qrCode)
    },
    bindPatient() {
      const id = this.docterDetail.UserId
      console.log('this.$refs.bindPatient', this.$refs.bindPatient)
      this.$refs.bindPatient.open(id)
    },
    bindAssistant() {
      const id = this.docterDetail.UserId
      this.$refs.bindAssistant.open(id)
    },
    async delAssistant(assistantId) {
      try {
        const doctorId = this.docterDetail.UserId
        await delDoctorAssistant({ doctorId, assistantId })
        this.$message.success('删除成功')
        this.init()
      } catch (error) {
        this.$message.error(error)
      }
    },
    rollback() {
      this.$router.go(-1)
    },
  },
}
</script> 
